package com.yylending.las.lending.quota.credit;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.*;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.common.utils.PermissionUtil;
import com.yylending.las.common.utils.StorageUtils;
import com.yylending.las.common.widgets.BorderEditText;
import com.yylending.las.common.widgets.CommonDialog;

/**
 * 提交征信授权认证码
 * Created by laixj on 2017/6/22.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */
public class AuthCommitActivity extends BaseActivity implements CreditPresenter.View, LocationPresenter.View {

	private final static String TAG = "AuthCommitActivity";
	private static final int REQUEST_CODE_GPS = 100;

	private final static int LOADER_ID_CREDIT = 1;
	private final static int LOADER_ID_LOCATE = 2;

	private final static String ARG_VERIFY_INFO = "arg_verify_info";
	@BindView(R.id.code_input)
	BorderEditText mCodeInput;
	@BindView(R.id.submit_btn)
	Button mSubmitBtn;
	@BindView(R.id.code_image)
	ImageView mCodeImage;
	@BindView(R.id.code_input_hint)
	TextView mCodeInputHint;
	@BindView(R.id.forgot_auth_code)
	TextView mForgotAuthCode;

	private CreditPresenter mCreditPresenter;
	private LocationPresenter mLocationPresenter;
	/**
	 * 定位信息
	 */
	private Location mLocation;
	/**
	 * 是否需要在定位成功之后自动提交验证码
	 */
	private boolean mAutoCommit;
	/**
	 * 认证码
	 */
	private String mVerifyCode;

	public static void startForResult(Fragment aty, int requestCode) {
		Intent i = new Intent(aty.getActivity(), AuthCommitActivity.class);
		aty.startActivityForResult(i, requestCode);
	}

	public static void startForResult(Fragment aty, int requestCode, String authCode) {
		Intent i = new Intent(aty.getActivity(), AuthCommitActivity.class);
		i.putExtra(Constants.BANK_AUTH_CODE, authCode);
		aty.startActivityForResult(i, requestCode);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_CREDIT:
				return new PresenterLoader<>(this, new CreditPresenter.Generator());
			case LOADER_ID_LOCATE:
				return new PresenterLoader<>(this, new LocationPresenter.Generator());
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_CREDIT:
				mCreditPresenter = (CreditPresenter) data;
				mCreditPresenter.attach(this);
				break;
			case LOADER_ID_LOCATE:
				mLocationPresenter = (LocationPresenter) data;
				mLocationPresenter.attach(this);
				PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				break;
		}
	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_credit_code_input);
		ButterKnife.bind(this);
		setTitle(R.string.credit_authority);
		String code = getIntent().getStringExtra(Constants.BANK_AUTH_CODE);
		if (TextUtils.isEmpty(code)) {
			String filePath = String.format(StorageUtils.SCREENSHOT_FILE_PATH_TEMPLATE, Environment.getExternalStorageDirectory().toString(), StorageUtils.SCREENSHOTS_DIR_NAME, StorageUtils.SCREENSHOT_FILE_NAME_TEMPLATE);
			try {
				Bitmap bitmap = BitmapFactory.decodeFile(filePath);
				if (null == bitmap) {
					mForgotAuthCode.setVisibility(View.VISIBLE);
					mCodeInputHint.setText(R.string.input_certification_code_hint1);
					mCodeImage.setVisibility(View.GONE);
				} else {
					mForgotAuthCode.setVisibility(View.GONE);
					mCodeInputHint.setText(R.string.input_certification_code_hint2);
					mCodeImage.setImageBitmap(bitmap);
					mCodeImage.setVisibility(View.VISIBLE);
				}
			} catch (Exception e) {
				mForgotAuthCode.setVisibility(View.VISIBLE);
				mCodeInputHint.setText(R.string.input_certification_code_hint1);
				mCodeImage.setVisibility(View.GONE);
			}
		} else {
			mCodeInput.setReadOnly(true);
			mCodeImage.setVisibility(View.GONE);
			mForgotAuthCode.setVisibility(View.GONE);
			mCodeInputHint.setText(R.string.input_certification_code_hint3);
			mCodeInput.setText(code);
			mCodeInput.setSelection(code.length());
		}
		getSupportLoaderManager().initLoader(LOADER_ID_CREDIT, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Global.setThirdPartyPageOpenedFlag(false);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		getSupportLoaderManager().destroyLoader(LOADER_ID_CREDIT);
		getSupportLoaderManager().destroyLoader(LOADER_ID_LOCATE);
		super.onDestroy();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@OnClick({R.id.submit_btn, R.id.forgot_auth_code})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.submit_btn:
				YJKD.hideInputWindow(this);
				mVerifyCode = mCodeInput.getText().toString().trim();
				if (TextUtils.isEmpty(mVerifyCode) || mVerifyCode.length() < 6) {
					showToast(R.string.credit_code_empty);
					return;
				}
				showLoading(true);
				if (null == mLocation) {
					mAutoCommit = true;
					PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				} else {
					mAutoCommit = false;
					commitAuthCode();
				}
				break;
			case R.id.forgot_auth_code:
				// 返回重现认证
				setResult(RESULT_CANCELED);
				finish();
				break;
		}
	}

	private void commitAuthCode() {
		mCreditPresenter.saveVerifyCode(mVerifyCode, String.valueOf(mLocation.longitude), String.valueOf(mLocation.latitude));
	}

	@Override
	public void getVerifyInfoSuccess(CreditModel.VerifyInfo verifyInfo) {

	}

	@Override
	public void creditHasLimited() {
		dismissLoading();
		Intent intent = new Intent();
		intent.putExtra(Constants.BANK_AUTH_LIMITED, true);
		setResult(RESULT_CANCELED, intent);
		finish();
	}

	@Override
	public void getVerifyInfoFail(String msg) {

	}

	@Override
	public void saveVerifyCodeSuccess() {
		dismissLoading();
		Intent intent = new Intent();
		intent.putExtra(Constants.BANK_AUTH_PASSED, true);
		setResult(RESULT_OK, intent);
		finish();
	}

	@Override
	public void saveVerifyCodeFail(String msg) {
		dismissLoading();
		Intent intent = new Intent();
		intent.putExtra(Constants.BANK_AUTH_PASSED, false);
		setResult(RESULT_OK, intent);
		finish();
	}

	@Override
	public void saveVerifyCodeRetCode(String retCode) {
		StatService.onEventWithSingleAttribute(this, StatIDSet.EVENT_ID_SUBMIT_AUTHENTICATION_CODES, retCode);

	}

	@Override
	public void onLocateSuccess(Location location) {
		mLocation = location;
		if (mAutoCommit)
			commitAuthCode();
	}

	@Override
	public void onLocateFail(boolean noPermission) {
		if (mAutoCommit) {
			dismissLoading();
			mAutoCommit = false;
		}
		if (noPermission) {
			showNeedLocationPermission();
		} else {
			if (com.yyfax.infrastructure.Constants.isConnected) {
				if(PermissionUtil.isGpsOPen(this)){
					if(PermissionUtil.isSdkUnderM()){
						showNeedLocationPermission();
					}else{
						showToast(R.string.locate_need_retry);
					}
				}else{
					showTwoBtnDialog(R.string.gps_permission_hint, R.string.go_to_settings, R.string.cancel, new CommonDialog.ButtonClickListener() {
						@Override
						public void onCancel(CommonDialog dialog) {
							dialog.dismiss();
						}

						@Override
						public void onConfirm(CommonDialog dialog) {
							//忽略手势密码
							Global.setThirdPartyPageOpenedFlag(true);
							//跳转GPS设置界面
							Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivityForResult(intent, REQUEST_CODE_GPS);
							dialog.dismiss();
						}
					}, true);
				}
			} else {
				showToast(R.string.locate_error_due_to_network);
			}
		}
	}

	@Override
	public void showDialog() {

	}

	@Override
	public void dismissDialog() {

	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.ACCESS_COARSE_LOCATION:
					if (permission.granted) {
						mLocationPresenter.startLocation(false);
					} else {
						if (mAutoCommit)
							dismissLoading();
						showNeedLocationPermission();
					}
					break;
				default:
					break;
			}

		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private void showNeedLocationPermission(){
		showTwoBtnDialog(getString(R.string.location_permission_hint, getString(R.string.app_name)), getString(R.string.go_to_settings), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				Global.setThirdPartyPageOpenedFlag(true);
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}

	@Override
	protected void onBackBtnPressed() {
		super.onBackBtnPressed();
		setResult(RESULT_CANCELED);
		finish();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		setResult(RESULT_CANCELED);
		finish();
	}
}
